package net.xo68.destiny.starter.worker.security;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.common.SystemConstants;
import net.xo68.destiny.starter.common.SchedulerCommonProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 工作节点接口调用认证过滤器
 * @author wuxie
 * @version 2020-11-3
 */
@Slf4j
public class WorkerAuthenticationFilter extends OncePerRequestFilter {

    private final SchedulerCommonProperties schedulerCommonProperties;

    public WorkerAuthenticationFilter(SchedulerCommonProperties schedulerCommonProperties) {
        this.schedulerCommonProperties = schedulerCommonProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String authToken = request.getHeader(SystemConstants.API_TOKEN_HEADER);
        if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(SystemConstants.API_TOKEN_PREFIX)) {
            authToken = authToken.substring(SystemConstants.API_TOKEN_PREFIX.length());
        } else {
            // 不按规范,不允许通过验证
            authToken = null;
        }

        //log.debug("request uri:{}", request.getRequestURI());
        if (StringUtils.isNotEmpty(authToken) && authToken.equals(schedulerCommonProperties.getApiAccessToken())) {
            UserDetail user = new UserDetail("ffffffffffffffffffffffffffffffff", "destiny");
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //log.debug("Authenticated user {}, setting security context", user.getUsername());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
